#!/usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
import sys
import os
import subprocess
import time
import hashlib
import urllib2
import urllib
import json


def colorPrint(color, print_string):
    color_dict = {
        'blue': '34',
        'red': '31',
        'green': '32',
        'yellow': '33',
        'pink': '35',
        'light-blue': '36'
    }
    if color in color_dict:
        print('\033[1;%sm%s\033[0m' % (color_dict[color], print_string))
    elif color in color_dict.values():
        print('\033[1;%sm%s\033[0m' % (color, print_string))
    else:
        print('颜色不支持')


class Res(object):
    def __init__(self, ip_file, game_code, key):
        # 从文件中读取要机器公网ip，并远程获取机器的内网ip
        self.game_code = game_code
        self.ip_dict = {}
        self.key = key
        self.my_time = int(time.time() * 1000)
        with open(ip_file, 'r') as f:
            for ip in f:
                self.ip_dict[ip.strip('\n')] = self.getLocalIP(ip)

    def runSubprocess(self, cmd):
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
        out = p.stdout.readlines().strip('\n').strip("'")
        return out

    def getLocalIP(self, remote_ip):
        cmd = ''' ssh %s -n "grep IPADDR /etc/sysconfig/network-scripts/ifcfg-eth0 | \
        sed -nr 's/IPADDR=(.*)/\1/gp'" ''' % remote_ip
        return self.runSubprocess(cmd)

    def urlRes(self, url, text):
        try:
            source = '{text}{time}{key}' .format(
                text=text, time=self.my_time, key=self.key)
            sign = hashlib.md5(source).hexdigest()
            args = {'text': text, 'time': self.my_time,
                    'game': self.game_code, 'sign': sign}
            data = urllib.urlencode(args)
            req = urllib2.Request(url, data)
            response = urllib2.urlopen(req)
            info_list = json.loads(response.read())
            success_list = info_list[u'infoList']
            error_list = info_list[u'errorList']
        except Exception, e:
            colorPrint('red', e)
            sys.exit(1)
        else:
            return success_list, error_list

    def importRes(self, url):
        info_list = []
        for remote_ip in self.ip_dict.keys():
            info_list.append('%s %s %s' % (
                self.game_code, remote_ip, self.ip_dict[remote_ip]))
        self.importRes(url, '\n'.join(info_list))


if __name__ == '__main':
    game_code = 'tx_zfd'
    key = 'Q2Bw6eLFR0udVxq4u1vpu8ySESDhmuLD'
    # key = '39a570f78e69b04c'
    url = ' http://center.6ght.com/game/in/hostImport/updateField/ip2Cmd'
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', action='store', dest='file', help='ip列表')

    options = parser.parse_args()
    if options.file is None or not os.path.isfile(options.file):
        print('没有指定列表文件或者列表文件不存在，退出脚本')
        sys.exit(1)
    else:
        res = Res(options.ip_file, game_code, key)
        res.importRes(url)
